#include <assert.h>
#include "libca.h"

static void _init(void) __attribute__((constructor));
static void _uninit(void) __attribute__((destructor));

extern int g_link_handle[LNK_ID_MAX];
static int g_init_state;

static void _init(void)
{
	int fd;
	int i;
	
	dbg_print(8, "%s: g_init_state=%d\n", __func__, g_init_state);
	if (g_init_state) {
		return;
	}
	g_init_state = 1;

	for (i = 0; i < LNK_ID_MAX; i++) {
		g_link_handle[i] = -1;
	}

	for (i = 0; i < MAX_CHAN_DI; i++) {
		fd = _link_create();
		assert(0 < fd);
		g_link_handle[LNK_ID_DI0 + i] = fd;
		dbg_print(8, "%s: cli-%d is created\n", __func__, LNK_ID_DI0 + i);
	}

	for (i = 0; i < MAX_CHAN_DO; i++) {
		fd = _link_create();
		assert(0 < fd);
		g_link_handle[LNK_ID_DO0 + i] = fd;
		dbg_print(8, "%s: cli-%d is created\n", __func__, LNK_ID_DO0 + i);
	}

	fd = _link_create();
	assert(0 < fd);
	g_link_handle[LNK_ID_ESAM] = fd;
	dbg_print(8, "%s: cli-%d is created\n", __func__, LNK_ID_ESAM);
}

static void _uninit(void)
{
	int i;

	for (i = 0; i < LNK_ID_MAX; i++) {
		if (0 < g_link_handle[i]) {
			close(g_link_handle[i]);
		}
	}
}

int _parse_id_from_io(void *ptr)
{
	ca_io_t *pio = (ca_io_t *) ptr;
	ca_di_t *pdi = (ca_di_t *) pio->ptr;
	ca_do_t *pdo = (ca_do_t *) pio->ptr;
	int id;

	switch (pio->cmd) {
		case CA_CMD_DI:
			id = LNK_ID_DI0 + pdi->ch;
			break;
		case CA_CMD_DO:
			id = LNK_ID_DO0 + pdo->ch;
			break;
		case CA_CMD_ESAM:
			id = LNK_ID_ESAM;
			break;
		default:
			id = -1;
			break;
	}
	dbg_print(8, "%s: id=%d\n", __func__, id);
	return id;
}
